package com.ocom.security.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 自定义{@link AccessDeniedHandler} ,重写 {@link OAuth2AccessDeniedHandler} 解决认证过的用户访问无权限资源时的异常
 */
@AllArgsConstructor
public class YoCiAccessDeniedHandler implements AccessDeniedHandler {

	private final ObjectMapper objectMapper;

	@Override
	public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException authException) throws IOException, ServletException {

		response.setCharacterEncoding("utf-8");
		response.setContentType("application/json;charset=UTF-8");
		response.setStatus(HttpStatus.FORBIDDEN.value());

		// xxx 合并代码时，抽取封装统一响应
		Map<String, Object> map = new HashMap<>();
		map.put("code", -1);
		map.put("msg", "没有权限，拒绝访问1");
		response.getWriter().print(objectMapper.writeValueAsString(map));
	}
}
